package com.longtop.framework.security;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

import com.longtop.framework.base.BaseService;
import com.longtop.framework.common.CacheUtil;
import com.longtop.framework.common.Constant;
import com.longtop.framework.sys.auth.model.TSysAuthData;
import com.longtop.framework.util.SpringBeanFactory;
import com.longtop.framework.util.StringUtil;

/**
 * 用户登陆session
 * 
 * @author 胡砥峰
 * 
 * @version 2.0
 */
public class SessionObject implements Serializable {

	public static final String BEAN_ID = "sessionObject";

	private static final long serialVersionUID = 1L;

	private String userId; // 用户ID
	private String loginName; // 登录名
	private String userName; // 用户姓名
	private String orgId; // 机构id
	private String orgName; // 机构名称
	private Date loginTime; // 登陆时间(yyyy-MM-dd HH:mm:ss)
	private String roleId; // 角色id
	private String roleName; // 角色名称
	private String ipAddr; // 登陆ip地址
	private List authOperMenuList; // 菜单权限码 数据集
	private List authOperFuncList; // 功能权限码 数据集

	// 扩展字段:
	private String duty;// 职务
	private String dutyName;// 职务名称
	private String sex;
	private String cardType;// 证件类型
	private String cardNo;// 证件号码
	private String isVirtual;// 是否是虚拟柜员

	private String orgLevel;// 机构次级
	private String parentOrgId;// 父级机构ID
	private String parentOrgName; // 父级机构名称
	private String orgLevelCode;// 机构次级

	// 首页URL，定制首页
	private String homeUrl;

	public String getUserId() {
		return userId;
	}

	public void setUserId(String userId) {
		this.userId = userId;
	}

	public String getLoginName() {
		return loginName;
	}

	public void setLoginName(String loginName) {
		this.loginName = loginName;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getOrgId() {
		return orgId;
	}

	public void setOrgId(String orgId) {
		this.orgId = orgId;
	}

	public String getOrgName() {
		return orgName;
	}

	public void setOrgName(String orgName) {
		this.orgName = orgName;
	}

	public Date getLoginTime() {
		return loginTime;
	}

	public void setLoginTime(Date loginTime) {
		this.loginTime = loginTime;
	}

	public String getRoleId() {
		return roleId;
	}

	public void setRoleId(String roleId) {
		this.roleId = roleId;
	}

	public String getRoleName() {
		return roleName;
	}

	public void setRoleName(String roleName) {
		this.roleName = roleName;
	}

	public String getIpAddr() {
		return ipAddr;
	}

	public void setIpAddr(String ipAddr) {
		this.ipAddr = ipAddr;
	}

	public List getAuthOperMenuList() {
		return authOperMenuList;
	}

	public void setAuthOperMenuList(List authOperMenuList) {
		this.authOperMenuList = authOperMenuList;
	}

	public List getAuthOperFuncList() {
		return authOperFuncList;
	}

	public void setAuthOperFuncList(List authOperFuncList) {
		this.authOperFuncList = authOperFuncList;
	}

	public String getDuty() {
		return duty;
	}

	public void setDuty(String duty) {
		this.duty = duty;
	}

	public String getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	public String getCardType() {
		return cardType;
	}

	public void setCardType(String cardType) {
		this.cardType = cardType;
	}

	public String getCardNo() {
		return cardNo;
	}

	public void setCardNo(String cardNo) {
		this.cardNo = cardNo;
	}

	public String getIsVirtual() {
		return isVirtual;
	}

	public void setIsVirtual(String isVirtual) {
		this.isVirtual = isVirtual;
	}

	public static long getSerialVersionUID() {
		return serialVersionUID;
	}

	/**
	 * 获取数据权限的过滤串
	 * 
	 * @param tableName
	 *            业务对象名称（表名） ex: T_TEST_SALE
	 * @param tableNameAliasName
	 *            业务对象别名（表别名） ex: a
	 * @param orgFieldName
	 *            数据表中的所属机构标识 ex：org_id
	 * @param userFieldName
	 *            数据表中的所属用户标识 ex：user_id(or create_man)
	 * @return a.org_id in('1', '2', '3' ) …… 还有其他几种情况,请看代码
	 */
	public String getGrantFilterSql(String tableName, String tableNameAliasName, String orgFieldName, String userFieldName) {

		BaseService baseService = SpringBeanFactory.getBean(BaseService.BEAN_ID);

		// 获取角色所有的数据权限
		List<TSysAuthData> authDataList = baseService.queryAll("from TSysAuthData where roleId='" + this.roleId + "'");
		if (authDataList == null || authDataList.size() == 0) {
			return "1=2";
		}

		// 当前用户的机构Id
		String currentOrgId = this.getOrgId();
		// 当前用户的用户Id
		String currentUserId = this.getUserId();

		// 返回字符串。
		StringBuffer stringBuffer = new StringBuffer();

		for (TSysAuthData authData : authDataList) {
			// 业务对象表名为所有表 or 等于tableName
			if (authData.getTableName().equals(tableName) || Constant.DATA_AUTH_ALL_TABLE_NAME.equals(authData.getTableName())) {
				// 情况1：机构数据
				if (Constant.DATA_AUTH_DATA_TYPE_ORG.equals(authData.getAuthType())) {
					if (StringUtil.isStrEmpty(orgFieldName)) {
						continue;
					}

					// 情况1.1：所有机构
					if (Constant.DATA_AUTH_ALL_ORG.equals(authData.getAuthScopeId())) {
						return "1=1";

					}// 情况1.2：用户所属机构
					else if (Constant.DATA_AUTH_OWNER.equals(authData.getAuthScopeId())) {
						// 情况1.2.1：不含下级
						if (Constant.DATA_AUTH_INCLUDE_SUB_NO.equals(authData.getIsIncludeSubOrg())) {
							if (stringBuffer.length() > 0) {
								stringBuffer.append(" or ");
							}
							if (!StringUtil.isStrEmpty(tableNameAliasName)) {
								stringBuffer.append(tableNameAliasName).append(".");
							}
							stringBuffer.append(orgFieldName).append("='").append(currentOrgId).append("'");
						}// 情况1.2.2：含下级
						else {
							String allOrgIds = CacheUtil.getAllOrgIds(currentOrgId, tableNameAliasName, orgFieldName);
							if (stringBuffer.length() > 0) {
								stringBuffer.append(" or ");
							}
							stringBuffer.append(allOrgIds);
						}
					}// 情况1.3：用户上级机构
					else if (Constant.DATA_AUTH_PARENT_ORG.equals(authData.getAuthScopeId())) {
						currentOrgId = CacheUtil.getSysOrgByOrgId(currentOrgId).getParentOrgId(); // 上级机构id

						// 情况1.2.1：不含下级
						if (Constant.DATA_AUTH_INCLUDE_SUB_NO.equals(authData.getIsIncludeSubOrg())) {
							if (stringBuffer.length() > 0) {
								stringBuffer.append(" or ");
							}
							if (!StringUtil.isStrEmpty(tableNameAliasName)) {
								stringBuffer.append(tableNameAliasName).append(".");
							}
							stringBuffer.append(orgFieldName).append("='").append(currentOrgId).append("'");
						}// 情况1.2.2：含下级
						else {
							String allOrgIds = CacheUtil.getAllOrgIds(currentOrgId, tableNameAliasName, orgFieldName);
							if (stringBuffer.length() > 0) {
								stringBuffer.append(" or ");
							}
							stringBuffer.append(allOrgIds);
						}
					}
					// 情况1.4：具体的一个一个单独机构
					else {
						// 情况1.3.1：不含下级
						if (Constant.DATA_AUTH_INCLUDE_SUB_NO.equals(authData.getIsIncludeSubOrg())) {
							if (stringBuffer.length() > 0) {
								stringBuffer.append(" or ");
							}
							if (!StringUtil.isStrEmpty(tableNameAliasName)) {
								stringBuffer.append(tableNameAliasName).append(".");
							}
							stringBuffer.append(orgFieldName).append("='").append(authData.getAuthScopeId()).append("'");
						}// 情况1.3.2：含下级
						else {
							String allOrgIds = CacheUtil.getAllOrgIds(authData.getAuthScopeId(), tableNameAliasName, orgFieldName);
							if (stringBuffer.length() > 0) {
								stringBuffer.append(" or ");
							}
							stringBuffer.append(allOrgIds);
						}
					}
				}// 情况2：个人数据
				else if (Constant.DATA_AUTH_DATA_TYPE_USER.equals(authData.getAuthType())) {
					if (StringUtil.isStrEmpty(userFieldName)) {
						continue;
					}

					// 情况2.1：用户本人数据
					if (Constant.DATA_AUTH_OWNER.equals(authData.getAuthScopeId())) {
						if (stringBuffer.length() > 0) {
							stringBuffer.append(" or ");
						}
						if (!StringUtil.isStrEmpty(tableNameAliasName)) {
							stringBuffer.append(tableNameAliasName).append(".");
						}
						stringBuffer.append(userFieldName).append("='").append(currentUserId).append("'");
					}// 情况2.2：具体的一个一个单独用户
					else {
						if (stringBuffer.length() > 0) {
							stringBuffer.append(" or ");
						}
						if (!StringUtil.isStrEmpty(tableNameAliasName)) {
							stringBuffer.append(tableNameAliasName).append(".");
						}
						stringBuffer.append(userFieldName).append("='").append(authData.getAuthScopeId()).append("'");
					}
				}

			}
		}

		if (stringBuffer.length() > 0) {
			stringBuffer.insert(0, "( ").append(" )");
		} else {
			// TODO 此处貌似要 return 1=2 待测试.
			return "1=2";
		}

		return stringBuffer.toString();
	}

	public String getDutyName() {
		return dutyName;
	}

	public void setDutyName(String dutyName) {
		this.dutyName = dutyName;
	}

	public String getHomeUrl() {
		return homeUrl;
	}

	public void setHomeUrl(String homeUrl) {
		this.homeUrl = homeUrl;
	}

	public String getOrgLevel() {
		return orgLevel;
	}

	public void setOrgLevel(String orgLevel) {
		this.orgLevel = orgLevel;
	}

	public String getParentOrgId() {
		return parentOrgId;
	}

	public void setParentOrgId(String parentOrgId) {
		this.parentOrgId = parentOrgId;
	}

	public String getParentOrgName() {
		return parentOrgName;
	}

	public void setParentOrgName(String parentOrgName) {
		this.parentOrgName = parentOrgName;
	}

	public String getOrgLevelCode() {
		return orgLevelCode;
	}

	public void setOrgLevelCode(String orgLevelCode) {
		this.orgLevelCode = orgLevelCode;
	}
}